package com.hm.service.service.token;

import com.hm.service.framework.session.TokenBean;
import com.hm.service.framework.session.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;


@Service
public class TokenService implements ITokenService {

    private static final Logger logger = LoggerFactory.getLogger(TokenService.class);


    @Qualifier("jedisPool")
    private final JedisPool jedisPool;

    public TokenService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    @Override
    public HashMap<String, String> verify(String token) {
        //token合法性校验
        HashMap<String, String> verify = TokenUtils.verify(token);
        String state = verify.get("state");
        if (state.equals("0")) {
            //校验通过的前提下-》判断单机登录
            HashMap<String, String> stand = new HashMap<>();
            TokenBean tokenBean = TokenUtils.decryptToken(token);
            String userId = tokenBean.getUserId();
            try (Jedis jedis = jedisPool.getResource()) {
                //根据userId获取对应的token
                boolean exists = jedis.exists(userId);
                if (exists) {
                    String latestToken = jedis.get(userId);
                    if (latestToken != null && latestToken.equals(token)) {
                        //校验通过
                        stand.put("state", "0");
                        stand.put("msg", "验证通过");
                    } else {
                        //token已经过期了-》被登陆了
                        stand.put("state", "7");
                        stand.put("msg", "已在其他设备登陆，请从新登录");
                    }
                } else {
                    stand.put("state", "8");
                    stand.put("msg", "无效的用户,请重新登录");
                }
            }
            return stand;
        } else {
            return verify;
        }
    }

    @Override
    public String generate(String userId) {
        String token = TokenUtils.generateToken(String.valueOf(userId));
        try (Jedis jedis = jedisPool.getResource()) {
            //userId和token对应
            jedis.set(userId, token);
            return token;
        }
    }

    @Override
    public String getUserId(String token) {
        TokenBean tokenBean = TokenUtils.decryptToken(token);
        return tokenBean.getUserId();
    }

}
